﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace IMT.Models
{
    public class NPOIHelp : Controller
    {
        //
        // GET: /NPOIHelp/
        public FileResult ExportExcel(object data, string ExcelName)
        {
            List<Dictionary<string, object>> NewData = new List<Dictionary<string, object>>();
            if (data is List<Dictionary<string, object>>)
            {
                try
                {
                    NewData = (List<Dictionary<string, object>>)data;
                }
                catch (Exception)
                {
                    return null;
                }
            }
            // 创建储存流
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //创建Excel文件的对象
            HSSFWorkbook book = new HSSFWorkbook();
            if (NewData.Count > 0)
            {
                // 创建一个首行加粗字体
                ICellStyle CStyle = book.CreateCellStyle();
                IFont font = book.CreateFont();
                font.Boldweight = (short)FontBoldWeight.Bold;
                CStyle.SetFont(font);
                //添加一个sheet
                ISheet sheet1 = book.CreateSheet("Sheet1");
                foreach (Dictionary<string, object> item in NewData)
                {
                    if (sheet1.PhysicalNumberOfRows == 0)
                    {
                        // 创建表头
                        IRow HeadRow = sheet1.CreateRow(0);
                        foreach (string key in NewData[0].Keys)
                        {
                            ICell cell = HeadRow.CreateCell(HeadRow.Cells.Count);
                            cell.SetCellValue(key);
                            cell.CellStyle = CStyle;
                            sheet1.SetColumnWidth(cell.ColumnIndex, 30 * 150);
                        }
                    }
                    IRow rowtemp = sheet1.CreateRow(sheet1.PhysicalNumberOfRows);
                    foreach (string key in item.Keys)
                    {
                        string value = item[key].ToString();
                        ICell cell = rowtemp.CreateCell(rowtemp.Cells.Count);
                        cell.SetCellValue(value);
                        sheet1.SetColumnWidth(cell.ColumnIndex, 30 * 150);
                    }
                    if (sheet1.LastRowNum == 65535)
                    {
                        sheet1 = book.CreateSheet("Sheet" + (book.Count + 1));
                    }
                }
            }
            else
            {
                //防止在没有数据的情况下，出现表格损坏提示！
                book.CreateSheet("Sheet1");
            }

            // 写入到流 
            book.Write(ms);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", ExcelName + ".xls");
        }

    }

}